package com.lb.shopguide.ui.fragment.boss;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.lb.baselib.http.ResponseCode;
import com.lb.baselib.http.SimpleLbObserver;
import com.lb.baselib.http.bean.BaseResponse;
import com.lb.shopguide.R;
import com.lb.shopguide.base.BaseMainFragment;
import com.lb.shopguide.entity.MerchantBean;
import com.lb.shopguide.event.boss.AddShopEventInMine;
import com.lb.shopguide.event.boss.ChangeMerchantNameEvent;
import com.lb.shopguide.event.guide.StartBrotherEvent;
import com.lb.shopguide.http.method.ApiMethodBoss;
import com.lb.baselib.http.SimpleObserverOnNextListener;
import com.lb.shopguide.ui.activity.BossMainActivity;
import com.lb.shopguide.util.json.JsonUtil;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener;
import com.trello.rxlifecycle2.android.FragmentEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by kang on 2017/12/23.
 */

public class FragmentBossMine extends BaseMainFragment {
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_merchant_name)
    TextView tvMerchantName;
    @BindView(R.id.tv_total_money)
    TextView tvTotalMoney;
    @BindView(R.id.layout_finance)
    RelativeLayout layoutFinance;
    @BindView(R.id.layout_store_summarize)
    RelativeLayout layoutStoreSummarize;
    @BindView(R.id.tv_already_store)
    TextView tvAlreadyStore;
    @BindView(R.id.tv_available_store)
    TextView tvAvailaStore;
    @BindView(R.id.tv_merchant_info_edit)
    TextView tvMerchantInfoEdit;
    @BindView(R.id.tv_rate_app)
    TextView tvRateApp;
    @BindView(R.id.tv_feedback)
    TextView tvFeedback;
    @BindView(R.id.tv_settings)
    TextView tvSettings;

    private MaterialHeader mMaterialHeader;

    private MerchantBean merchantBean;



    public static FragmentBossMine newInstance() {
        return new FragmentBossMine();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_boss_mine;
    }

    @Override
    public void initData() {
        sendRequestGetMerchantInfo();
        EventBus.getDefault().register(this);
    }

    @Override
    public void initView() {
        mMaterialHeader = (MaterialHeader) refreshLayout.getRefreshHeader();
        initListener();
    }

    @Override
    public void finishRefresh() {
        refreshLayout.finishRefresh(true);
    }

    @Override
    public void sessionOutOfDate() {
        ((BossMainActivity) getActivity()).onSessionOutOfDate();
        finishRefresh();
    }

    @Override
    public void requestError(String error) {
        ToastUtils.showShort(error);
        finishRefresh();
    }

    private void initListener() {
        refreshLayout.setOnRefreshListener(new OnMultiPurposeListener() {
            @Override
            public void onHeaderPulling(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderReleased(RefreshHeader header, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderReleasing(RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderStartAnimator(RefreshHeader header, int headerHeight, int extendHeight) {

            }

            @Override
            public void onHeaderFinish(RefreshHeader header, boolean success) {

            }

            @Override
            public void onFooterPulling(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterReleased(RefreshFooter footer, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterReleasing(RefreshFooter footer, float percent, int offset, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterStartAnimator(RefreshFooter footer, int footerHeight, int extendHeight) {

            }

            @Override
            public void onFooterFinish(RefreshFooter footer, boolean success) {

            }

            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {

            }

            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                sendRequestGetMerchantInfo();
            }

            @Override
            public void onStateChanged(RefreshLayout refreshLayout, RefreshState oldState, RefreshState newState) {

            }
        });
    }

    private void sendRequestGetMerchantInfo() {
        SimpleObserverOnNextListener<BaseResponse> listener = new SimpleObserverOnNextListener<BaseResponse>() {

            @Override
            public void onNext(BaseResponse response) {
                if (response.getReturnCode() == ResponseCode.RESPONSE_SUCCESS) {
                    merchantBean = (MerchantBean) JsonUtil.getObject(response.getReturnContent(), MerchantBean.class);
                    bindMerchantInfo(merchantBean);
                    refreshLayout.finishRefresh(true);
                }
            }

        };
        ApiMethodBoss.getMerchantInfo(new SimpleLbObserver(listener, otherListener),this, FragmentEvent.DESTROY_VIEW);
    }

    private void bindMerchantInfo(MerchantBean merchantBean) {
        tvMerchantName.setText(merchantBean.getMerchantName());
        tvTotalMoney.setText(merchantBean.getAccountBalance());

        tvAvailaStore.setText(merchantBean.getStoreNum());
        tvAlreadyStore.setText(merchantBean.getActualStoreSum());
    }

    private void rate() {
        Uri uri = Uri.parse("market://details?id=" + mContext.getPackageName());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY |
                Intent.FLAG_ACTIVITY_NEW_DOCUMENT | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            startActivity(new Intent(Intent.ACTION_VIEW,
                    Uri.parse("http://play.google.com/store/apps/details?id=" + mContext.getPackageName())));
        }
    }

    @Override
    public String getPageTag() {
        return FragmentBossMine.class.getName();
    }

    @OnClick(R.id.layout_finance)
    void finance() {
        if (merchantBean != null) {
            EventBus.getDefault().post(new StartBrotherEvent(FragmentFinanceManage.newInstance(merchantBean)));
        }
    }

    @OnClick(R.id.tv_settings)
    void settings() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentBossSettings.newInstance()));
    }

    @OnClick(R.id.layout_store_summarize)
    void storeSummarize() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentShopManage.newInstance()));
    }

    @OnClick(R.id.tv_merchant_name)
    void merchantNameClick() {
        //EventBus.getDefault().post(new StartBrotherEvent(FragmentMerchantInfo.newInstance()));
    }

    @OnClick(R.id.tv_merchant_info_edit)
    void merchantInfoEdit() {
        if (merchantBean != null) {
            EventBus.getDefault().post(new StartBrotherEvent(FragmentEditMerchantInfo.newInstance(merchantBean)));
        }
    }

    @OnClick(R.id.tv_feedback)
    void feedback() {
        EventBus.getDefault().post(new StartBrotherEvent(FragmentFeedback.newInstance()));
    }

    @OnClick(R.id.tv_rate_app)
    void rateApp() {
        rate();
    }


    @Subscribe
    public void onMerchantNameChange(ChangeMerchantNameEvent event) {
        merchantBean = event.getMerchantBean();
        tvMerchantName.setText(merchantBean.getMerchantName());
    }

    @Subscribe
    public void onAddShop(AddShopEventInMine event) {
        sendRequestGetMerchantInfo();
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

}
